package com.hit.basmath.interview.we_meet.kwai;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * author:Charies Gavin
 * date:2021/1/28,19:31
 * https:github.com/guobinhit
 * description: 两个线程交替打印奇偶数
 */
public class PrintOddEvenNum {

    private int n;
    private Semaphore odd = new Semaphore(1);
    private Semaphore even = new Semaphore(0);

    public PrintOddEvenNum(int n) {
        this.n = n;
    }

    public void printOdd() {
        for (int i = 1; i <= n; i += 2) {
            try {
                odd.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("打印奇数：" + i);
            even.release();
        }

    }

    public void printEven() {
        for (int i = 2; i <= n; i += 2) {
            try {
                even.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("打印偶数：" + i);
            odd.release();
        }
    }

    public static void main(String[] args) {
        PrintOddEvenNum printNum = new PrintOddEvenNum(10);
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(printNum::printOdd);
        executorService.submit(printNum::printEven);
        executorService.shutdown();
    }
}